const $get = require('./axios.js')
const fs = require('fs')
const cheerio = require('cheerio')

const getRoleList = async () => {
    const response = await $get({
        url: 'https://api-static.mihoyo.com/common/blackboard/ys_obc/v1/home/content/list?app_sn=ys_obc&channel_id=189'
    })
    let role_list = response.data.data.list[0].children[0].list
    let list = []
    role_list.map((item) => {
        if (item.title !== '旅行者（空）') {
            if (item.title === '旅行者（荧）') {
                let info = JSON.parse(JSON.parse(item.ext).c_25.filter.text)
                let level = ''
                let weapon = ''
                let type = []
                for (let i in info) {
                    let info_arr = info[i].split('/')
                    switch (info_arr[0]) {
                        case '星级':
                            level = info_arr[1]
                            break;
                        case '元素':
                            type.push(info_arr[1])
                            break;
                        case '武器':
                            weapon = info_arr[1]
                            break;
                    }
                }
                for (let i in type) {
                    list.push({
                        id: item.content_id,
                        name: `旅行者(${type[i]})`,
                        image: item.icon,
                        level: textClear(level),
                        type: textClear(type[i]),
                        weapon: textClear(weapon),
                    })
                }
            } else {
                let info = JSON.parse(JSON.parse(item.ext).c_25.filter.text)
                let level = ''
                let type = ''
                let weapon = ''
                for (let i in info) {
                    let info_arr = info[i].split('/')
                    switch (info_arr[0]) {
                        case '星级':
                            level = info_arr[1]
                            break;
                        case '元素':
                            type = info_arr[1]
                            break;
                        case '武器':
                            weapon = info_arr[1]
                            break;
                    }
                }
                list.push({
                    id: item.content_id,
                    name: item.title,
                    image: item.icon,
                    level: textClear(level),
                    type: textClear(type),
                    weapon: textClear(weapon),
                })
            }
        }
    })
    fs.writeFile('./role.json', JSON.stringify(list, null, 2), {flag: "w+"}, function (err) {
        if (!err) {
            console.log('getRoleList done:')
            getRoleInfoLoop()
        } else {
            console.log('log save error:', err)
        }
    });
}
const saveUpInfo = (id, response) => {
    let html = response.data.data.content.contents[0].text
    let $ = cheerio.load(html);
    let part = $('.obc-tmpl-character .obc-tmpl__switch-list table')
    let num_arr = $(part[0]).find('li .obc-tmpl__icon-text-num')
    let stone = []
    let boss = {name: '', image: ''}
    let pick = {name: '', image: ''}
    let monster = []
    num_arr.each((index, item) => {
        let name = $(item).find('.obc-tmpl__icon-text').text()
        let image = $(item).find('img').attr('src')
        switch (index) {
            case 0:
            case 1:
            case 2:
            case 3:
                stone.push({name: textClear(name), image})
                break;
        }
        let i = id === 4073 ? index + 1 : index
        switch (i) {
            case 4:
                boss = {name: textClear(name), image}
                break;
            case 5:
                pick = {name: textClear(name), image}
                break;
            case 6:
            case 7:
            case 8:
                monster.push({name: textClear(name), image})
                break;
        }
    })
    fs.writeFile(`./up/${id}.json`, JSON.stringify({
        stone, boss, pick, monster
    }, null, 2), {flag: "w+"}, function (err) {
        if (!err) {
            console.log('saveUpInfo done:' + id)
        } else {
            console.log('log save error:', err)
        }
    });
}
const saveSkillInfo = (id, response) => {
    let html = response.data.data.content.contents[1].text
    let $ = cheerio.load(html);
    let part = $('.obc-tmpl-character')
    let l = []
    part.each((key, item) => {
        if ((id !== 4073 && key === 0) || (id === 4073 && key % 2 === 1)) {
            let group = $(item).find('table tr')
            let ll_ii = []
            group.each((kk, ii) => {
                if ($(ii).find('.obc-tmpl__scroll-td').text().indexOf('升级材料') !== -1) {
                    let tdg = $(ii).find('td')
                    tdg.each((kkk, iii) => {
                        if ([2, 3, 4, 5, 6, 7, 8, 9, 10].indexOf(kkk) !== -1) {
                            let line = $(iii).find('.obc-tmpl__icon-text-num')
                            let ll_iii = []
                            line.each((kkkk, iiii) => {
                                let name = $(iiii).find('.obc-tmpl__icon-text').text()
                                let image = $(iiii).find('img').attr('src')
                                ll_iii.push({name: textClear(name), image})
                            })
                            if (ll_ii.length < 9) ll_ii.push(ll_iii)
                        }
                    })
                }
            })
            l.push(ll_ii)
        }
    })
    fs.writeFile(`./skill/${id}.json`, JSON.stringify(l, null, 2), {flag: "w+"}, function (err) {
        if (!err) {
            console.log('saveSkillInfo done:' + id)
        } else {
            console.log('log save error:', err)
        }
    });
}
const getRoleInfo = async (id) => {
    const response = await $get({
        url: 'https://api-static.mihoyo.com/common/blackboard/ys_obc/v1/content/info?app_sn=ys_obc&content_id=' + id
    })
    saveUpInfo(id, response)
    saveSkillInfo(id, response)
}
const getRoleInfoLoop = () => {
    fs.readFile('./role.json', async (err, data) => {
        if (err) throw err
        let role = JSON.parse(data.toString())
        for (let i in role) {
            await getRoleInfo(role[i].id)
        }
        await getWeaponList()
    })
}
const getWeaponInfoLoop = () => {
    fs.readFile('./weapon.json', async (err, data) => {
        if (err) throw err
        let role = JSON.parse(data.toString())
        for (let i in role) {
            await getWeaponInfo(role[i].id)
        }
        await getArtifactList()
    })
}
const getArtifactList = async () => {
    const response = await $get({
        url: 'https://api-static.mihoyo.com/common/blackboard/ys_obc/v1/home/content/list?app_sn=ys_obc&channel_id=189'
    })
    let artifact_list = response.data.data.list[0].children[2].list
    let list = []
    artifact_list.map((item) => {
        list.push({
            id: item.content_id, name: textClear(item.title), image: item.icon
        })
    })
    fs.writeFile('./artifact.json', JSON.stringify(list, null, 2), {flag: "w+"}, function (err) {
        if (!err) {
            console.log('getArtifactList done:')
            clearRoleData()
        } else {
            console.log('log save error:', err)
        }
    })
}
const getWeaponList = async () => {
    const response = await $get({
        url: 'https://api-static.mihoyo.com/common/blackboard/ys_obc/v1/home/content/list?app_sn=ys_obc&channel_id=189'
    })
    let weapon_list = response.data.data.list[0].children[1].list
    let list = []
    weapon_list.map((item) => {
        let info = JSON.parse(JSON.parse(item.ext).c_5.filter.text)
        let level = ''
        let type = ''
        for (let i in info) {
            let info_arr = info[i].split('/')
            switch (info_arr[0]) {
                case '武器星级':
                    level = info_arr[1]
                    break;
                case '武器类型':
                    type = info_arr[1]
                    break;
            }
        }
        list.push({
            id: item.content_id,
            name: textClear(item.title),
            image: item.icon,
            level: textClear(level),
            type: textClear(type),
        })
    })
    fs.writeFile('./weapon.json', JSON.stringify(list, null, 2), {flag: "w+"}, function (err) {
        if (!err) {
            console.log('getWeaponList done:')
        } else {
            console.log('log save error:', err)
        }
    });
    getWeaponInfoLoop()
}
const saveWeaponInfo = (id, response) => {
    let html = response.data.data.content.contents[0].text
    let $ = cheerio.load(html);
    let part = $('.obc-tmpl__switch-list .obc-tmpl__switch-item')
    let list = []
    part.each((k, i) => {
        if ([1, 2, 3, 4, 5, 6].indexOf(k) !== -1) {
            let lll = []
            let group = $(i).find('tbody')
            let table = $(group[1]).find('.obc-tmpl__icon-text-num')
            table.each((kk, ii) => {
                let name = $(ii).find('.obc-tmpl__icon-text').text()
                let image = $(ii).find('img').attr('src')
                lll.push({name: textClear(name), image})
            })
            if (lll.length) list.push(lll)
        }
    })
    fs.writeFile(`./weapon/${id}.json`, JSON.stringify(list, null, 2), {flag: "w+"}, function (err) {
        if (!err) {
            console.log('saveWeaponInfo done:' + id)
        } else {
            console.log('log save error:', err)
        }
    });
}
const getWeaponInfo = async (id) => {
    const response = await $get({
        url: 'https://api-static.mihoyo.com/common/blackboard/ys_obc/v1/content/info?app_sn=ys_obc&content_id=' + id
    })
    saveWeaponInfo(id, response)
}
const data_count = {
    skill: [{
        book: 3, monster: 6, week: 0
    }, {
        book: 2, monster: 3, week: 0
    }, {
        book: 4, monster: 4, week: 0
    }, {
        book: 6, monster: 6, week: 0
    }, {
        book: 9, monster: 9, week: 0
    }, {
        book: 4, monster: 4, week: 1
    }, {
        book: 6, monster: 6, week: 1
    }, {
        book: 12, monster: 9, week: 2
    }, {
        book: 16, monster: 12, week: 2
    }], up: [{
        stone: [2, 1], boss: 0, pick: 3, monster: [1, 3]
    }, {
        stone: [3, 3], boss: 2, pick: 10, monster: [1, 15]
    }, {
        stone: [3, 6], boss: 4, pick: 20, monster: [2, 12]
    }, {
        stone: [4, 3], boss: 8, pick: 30, monster: [2, 18]
    }, {
        stone: [4, 6], boss: 12, pick: 45, monster: [3, 12]
    }, {
        stone: [5, 6], boss: 20, pick: 60, monster: [3, 24]
    }], weapon: [[{
        item: [2, 1], elite: [2, 1], monster: [1, 1]
    }, {
        item: [3, 1], elite: [2, 4], monster: [1, 2]
    }, {
        item: [3, 2], elite: [3, 2], monster: [2, 2]
    }, {
        item: [4, 1], elite: [3, 4], monster: [2, 3]
    }], [{
        item: [2, 1], elite: [2, 1], monster: [1, 1]
    }, {
        item: [3, 1], elite: [2, 5], monster: [1, 4]
    }, {
        item: [3, 3], elite: [3, 3], monster: [2, 3]
    }, {
        item: [4, 1], elite: [3, 5], monster: [2, 4]
    }], [{
        item: [2, 2], elite: [2, 2], monster: [1, 1]
    }, {
        item: [3, 2], elite: [2, 8], monster: [1, 5]
    }, {
        item: [3, 4], elite: [3, 4], monster: [2, 4]
    }, {
        item: [4, 2], elite: [3, 8], monster: [2, 6]
    }, {
        item: [4, 4], elite: [4, 6], monster: [3, 4]
    }, {
        item: [5, 3], elite: [4, 12], monster: [3, 8]
    }], [{
        item: [2, 3], elite: [2, 3], monster: [1, 2]
    }, {
        item: [3, 3], elite: [2, 12], monster: [1, 8]
    }, {
        item: [3, 6], elite: [3, 6], monster: [2, 6]
    }, {
        item: [4, 3], elite: [3, 12], monster: [2, 9]
    }, {
        item: [4, 6], elite: [4, 9], monster: [3, 6]
    }, {
        item: [5, 4], elite: [4, 18], monster: [3, 12]
    }], [{
        item: [2, 5], elite: [2, 5], monster: [1, 3]
    }, {
        item: [3, 5], elite: [2, 18], monster: [1, 12]
    }, {
        item: [3, 9], elite: [3, 9], monster: [2, 9]
    }, {
        item: [4, 5], elite: [3, 18], monster: [2, 14]
    }, {
        item: [4, 9], elite: [4, 14], monster: [3, 9]
    }, {
        item: [5, 6], elite: [4, 27], monster: [3, 18]
    }]]
}
const clearRoleData = () => {
    let list = {
        count: data_count, role: [], type: [], stone: {}, monster: {}, boss: {}, pick: {}, book: {}, week: {}, crown: ''
    }
    fs.readFile('./role.json', async (err, data) => {
        if (err) throw err
        let role = JSON.parse(data.toString())
        for (let i in role) {
            let item = {
                ...role[i], stone: [], boss: '', pick: '', monster: [], skill: []
            }
            if (list.type.indexOf(role[i].type) === -1) list.type.push(role[i].type)
            fs.readFile(`./up/${role[i].id}.json`, (err, item_data) => {
                if (err) throw err
                let role_up = JSON.parse(item_data.toString())
                item.stone = role_up.stone.map(mi => mi.name)
                if (role[i].id !== 4073) item.boss = role_up.boss.name
                item.pick = role_up.pick.name
                item.monster = role_up.monster.map(mi => mi.name)
                for (let ii = 0; ii < 4; ii++) {
                    list.stone[role_up.stone[ii].name] = role_up.stone[ii].image
                }
                if (role[i].id !== 4073) list.boss[role_up.boss.name] = role_up.boss.image
                list.pick[role_up.pick.name] = role_up.pick.image
                for (let ii = 0; ii < 3; ii++) {
                    list.monster[role_up.monster[ii].name] = role_up.monster[ii].image
                }
                fs.readFile(`./skill/${role[i].id}.json`, (err, skill_data) => {
                    if (err) throw err
                    let role_skill = JSON.parse(skill_data.toString())
                    let skill_info = role_skill[0]
                    if (role[i].id === 4073) {
                        switch (item.name) {
                            case '旅行者(雷)':
                                skill_info = role_skill[1]
                                break;
                            case '旅行者(岩)':
                                skill_info = role_skill[2]
                                break;
                            case '旅行者(风)':
                                skill_info = role_skill[3]
                                break;
                        }
                    }
                    for (let ii = 0; ii < 9; ii++) {
                        let book = skill_info[ii][0].name
                        let monster = skill_info[ii][1].name
                        let item_skill = {
                            book, monster
                        }
                        if (!!skill_info[ii][2]) {
                            item_skill.week = skill_info[ii][2].name
                        }
                        item.skill.push(item_skill)
                        list.book[skill_info[ii][0].name] = skill_info[ii][0].image
                        list.monster[skill_info[ii][1].name] = skill_info[ii][1].image
                    }
                    list.week[skill_info[8][2].name] = skill_info[8][2].image
                    list.crown = skill_info[8][3].image
                    list.role.push(item)
                    if (role.length === list.role.length) {
                        clearWeaponData(list)
                    }
                })
            })
        }
    })
}
const clearWeaponData = (list) => {
    list = {
        ...list, weapon: [], item: {}, elite: {}
    }
    fs.readFile('./weapon.json', async (err, data) => {
        if (err) throw err
        let weapon = JSON.parse(data.toString())
        for (let i in weapon) {
            let item = {
                ...weapon[i], item: [], elite: [], monster: []
            }
            fs.readFile(`./weapon/${weapon[i].id}.json`, (err, item_data) => {
                if (err) throw err
                let weapon_info = JSON.parse(item_data.toString())
                for (let ii in weapon_info) {
                    if (item.item.indexOf(weapon_info[ii][0].name) === -1) {
                        item.item.push(weapon_info[ii][0].name)
                    }
                    if (item.elite.indexOf(weapon_info[ii][1].name) === -1) {
                        item.elite.push(weapon_info[ii][1].name)
                    }
                    if (item.monster.indexOf(weapon_info[ii][2].name) === -1) {
                        item.monster.push(weapon_info[ii][2].name)
                    }
                    list.item[weapon_info[ii][0].name] = weapon_info[ii][0].image
                    list.elite[weapon_info[ii][1].name] = weapon_info[ii][1].image
                    list.monster[weapon_info[ii][2].name] = weapon_info[ii][2].image
                }
                list.weapon.push(item)
                if (weapon.length === list.weapon.length) {
                    clearArtifactData(list)
                }
            })
        }
    })
}
const clearArtifactData = (list) => {
    fs.readFile('./artifact.json', async (err, data) => {
        if (err) throw err
        let artifact = JSON.parse(data.toString())
        list = {
            ...list, artifact
        }
        saveData(list)
    })

}
const saveData = (data) => {
    fs.writeFile(`./data.json`, JSON.stringify(data, null, 2), {flag: "w+"}, function (err) {
        if (!err) {
            console.log('saveData done:')
        } else {
            console.log('log save error:', err)
        }
    });
}
const textClear = (text) => {
    text = text.split(' ').join('')
    text = text.split('「').join('')
    text = text.split('」').join('')
    return text
}
const startRun = async () => {
    if (!fs.existsSync('./skill')) fs.mkdirSync('./skill')
    if (!fs.existsSync('./up')) fs.mkdirSync('./up')
    if (!fs.existsSync('./weapon')) fs.mkdirSync('./weapon')
    await getRoleList()
}
(async () => {
    await startRun() // 入口
    // await getRoleList()
    // clearRoleData()
    // await getArtifactList()
    // getWeaponInfoLoop()
    // await getWeaponList()
    // getRoleInfoLoop()
    // await getWeaponInfo(5110)
    // await getRoleInfo(76)
    // await getRoleInfo(4073)
})()



